import React, { useState,useMemo } from 'react'
import styles from "../assets/styles/todolist.module.css"

export default function TodoList() {
    const [lists, setLists] = useState([
        { id: 1, taskName: "吃饭", state: true },
        { id: 2, taskName: "睡觉", state: false },
        { id: 3, taskName: "打豆豆", state: false }
    ])
    // all done undone
    const [btnStatus,setBtnStatus] = useState("all")

    //语法规则，指定要监控的数据，得到新的结果
    const newList = useMemo(()=>{
        switch(btnStatus){
            case "all":return lists
            case "done":return lists.filter(item=>item.state)
            case "undone":return lists.filter(item=>!item.state)
        }
    },[btnStatus])
    /**
     * 函数定义有两种：
     * 普通函数
     * 箭头函数
     * React更新策略，基本数据对比值
     * 如果是引用类型，对比地址是否发生变化
     */

    const changeStatus = (id) => {
        const newArray = [...lists]
        const index = lists.findIndex(element => element.id == id)

        newArray.splice(index, 1)
        // console.log(lists);
        setLists(newArray)
    }
    const changeState = (id) => {
        //得到要操作对象
        const newArray = [...lists]
        const element = newArray.find(item => item.id == id)
        element.state = !element.state
        console.log(element);
        setLists(newArray)

    }
    const btnChangeState = (event)=>{
        console.log(event.target.index);
        const btnType = event.target.getAttribute("index")
        setBtnStatus(btnType)
    }
    return (
        <div>
            <h2>任务列表</h2>
            <input type="text" />
            <button>添加</button>
            <ul>
                {newList.map(item => {
                    return (<li key={item.id}>
                        <span onDoubleClick={() => changeState(item.id)} className={item.state ? styles.done : ""}>{item.taskName}</span>
                        <button onClick={() => changeStatus(item.id)}>删除</button>
                    </li>)
                })}
            </ul>
            <p>总任务{lists.length}个/完成{lists.filter(item => item.state).length}个</p>
            <div onClick={btnChangeState}>
                <button index="all">全部</button>
                <button index="done">已完成</button>
                <button index="undone">未完成</button>
            </div>
        </div>
    )
}
